package com.niuke;

import java.util.HashMap;

/**
 * @ClassName : NC28
 * @Author : kele
 * @Date: 2023/4/8 17:59
 * @Description :
 */
public class NC28 {

    public static String minWindow(String S, String T) {

        HashMap<Character, Integer> need = new HashMap<>();
        HashMap<Character, Integer> join = new HashMap<>();

        for (char c : T.toCharArray()) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }
        if (T.length() > S.length()) {
            return "";
        }

        int start = 0, matchNum = 0;
        int left = 0, right = 0;
        int max = Integer.MAX_VALUE;

        while (right < S.length()) {

            char c = S.charAt(right);
            if (need.containsKey(c)) {
                join.put(c, join.getOrDefault(c, 0) + 1);
                if (join.get(c).equals(need.get(c))) {
                    matchNum++;
                }

                while (matchNum == need.size()) {

                    if (max > right - left) {
                        max = right - left;
                        start = left;
                    }

                    char c_l = S.charAt(left);

                    if (need.containsKey(c_l)) {
                        join.put(c_l, join.get(c_l) - 1);
                        if (need.get(c_l) > join.get(c_l)) {
                            matchNum--;
                        }
                    }
                    left++;
                }
            }
            right++;
        }
        return max == Integer.MAX_VALUE ? "" : S.substring(start, start + max + 1);
    }

    public static void main(String[] args) {
        System.out.println(minWindow("XDOYEZODEYXNZ", "XYZ"));
    }
}
